package com.ysq.www.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import com.ysq.www.common.utils.h5.H5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 用户主表
 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectCardById(Integer userId) {
        return userMapper.selectCardById(userId);
    }

    /**
     * 静默授权登录
     * @param code 微信授权码
     * @param asId 协会id
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg silentLogin(String code, Integer asId) {
        Map<String, String> rMap = H5Utils.getOpenId(code, asId);
        if (rMap.containsKey("errorMsg")) return ResultMsg.UPDATE_ERROR.setNewMsg("授权登录失败");
        String openId = rMap.get("openId");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("open_id",openId);
        User user = userMapper.selectOne(wrapper);
        if (user == null){//用户不存在，新增用户
            User nu = new User();
            nu.setOpenId(openId);
            nu.setAsId(asId);
            nu.setCreateTime(Comm.getNow());
            nu.setUpdateTime(Comm.getNow());
            nu.setStatus(0);
            this.save(nu);
            User user1 = userMapper.selectById(nu.getId());
            return ResultMsg.SUCCESS.setNewMsg("授权登录成功").setNewData(user1);
        }
        return ResultMsg.SUCCESS.setNewData("授权登陆成功").setNewData(user);
    }
}
